const emailModule = require('./email')
const const_module = require('./const')
const grpc = require('@grpc/grpc-js')
const message_proto = require('./proto')
const { v4: uuidv4 } = require('uuid')

// Added error code constants for better readability
const { Errors } = const_module;

async function GetVarifyCode(call, callback) {
    console.log("Request received for email:", call.request.email);
    
    try {
        const uniqueId = uuidv4();  // Added const for immutability
        console.log("Generated verification code:", uniqueId);
        
        const text_str = `你的验证码为: ${uniqueId} 请在三分钟内注册`;

        const mailOptions = {
            from: "17633104583@163.com",
            to: call.request.email,
            subject: "验证码",
            text: text_str
        };

        // Added more detailed logging
        console.log("Attempting to send email to:", call.request.email);
        
        // If SendMail returns a promise that might reject even on success,
        // you might need to modify the email module
        const send_res = await emailModule.SendMail(mailOptions);
        
        console.log("Email sent successfully. Response:", send_res);
        
        callback(null, {
            email: call.request.email,
            error: Errors.Success,
            code: uniqueId
        });

    } catch (error) {
        console.error("Error sending verification email:", error);
        
        callback(null, {
            email: call.request.email,
            error: Errors.Exception,
            code: ""  // Added empty code for consistency
        });
    }
}

function main() {
    const server = new grpc.Server();
    server.addService(message_proto.VarifyService.service, { GetVarifyCode });

    server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), (error, port) => {
        if (error) {
            console.error("Failed to bind server:", error);
            return;
        }
        
        server.start();
        console.log(`gRPC server started on port ${port}`);
    });
}

main();